package edu.ctbu.ctbujsj.webapi;


import edu.ctbu.ctbujsj.domain.Student;
import edu.ctbu.ctbujsj.service.StudentService;
import edu.ctbu.ctbujsj.vo.BTPageDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.sql.Date;
import java.text.SimpleDateFormat;

@RestController
@Slf4j
public class StudentRestController {



    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    private StudentService studentService;

    /**
     * 基本分页
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/webapi/student/list")
    public BTPageDO<Student> list(int offset, int limit){

        int pageIndex=offset/limit;
        int pageSize=limit;

        Page<Student> myList=studentService.findByPage(pageIndex,pageSize);

        BTPageDO<Student> stuList=new BTPageDO<Student>();
        stuList.setLimit(pageSize);
        stuList.setOffset(pageIndex);
        stuList.setRows(myList.getContent());
        Long total=myList.getTotalElements();
        stuList.setTotal(total.intValue());

        return  stuList;


    }



    @PostMapping(value = "/webapi/student/add")
    public int add(@Valid Student student, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;
        }
        studentService.add(student);

        Long  myid=  student.getId();

        return myid.intValue();

    }
}
